//
//  appendPhotosCollectionView.swift
//  weibo1
//
//  Created by 李进 on 15/10/26.
//  Copyright © 2015年 李进. All rights reserved.
//

import UIKit

class appendPhotosCollectionView: UICollectionView {

    init(){
        
        super.init(frame: CGRectZero, collectionViewLayout: appendPhotosCVFlowLayout())
        backgroundColor = UIColor.lightGrayColor()
        
        //注册cell
        registerClass(appendPhotosCollectionViewCell.self, forCellWithReuseIdentifier: appendPhotosCollectionViewCellId)
        
        
        dataSource = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
   private lazy var arrayList = [UIImage]()
    
    /// MARK: -设置流水布局
    class appendPhotosCVFlowLayout: UICollectionViewFlowLayout{
        
        let cellMargin: CGFloat = UIScreen.mainScreen().scale * 4
        
        override func prepareLayout() {
            super.prepareLayout()
            let count: CGFloat = 4
            //let margin = UIScreen.mainScreen().scale * 4
            let w = (collectionView!.bounds.width - (count + 1) * cellMargin) / count
            minimumLineSpacing = cellMargin
            minimumInteritemSpacing = cellMargin
            scrollDirection = .Vertical
            itemSize = CGSizeMake(w, w)
            sectionInset = UIEdgeInsetsMake(cellMargin, cellMargin, 0, cellMargin)
        }
        
    }

}

// MARK: - 实现添加图片视图的的数据源方法
extension appendPhotosCollectionView: UICollectionViewDataSource, UICollectionViewDelegate{
    
    /// 实现collectionview的数据源方法

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //print(arrayList.count)
        return (arrayList.count + 1)
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(appendPhotosCollectionViewCellId, forIndexPath: indexPath) as! appendPhotosCollectionViewCell
        
        cell.appimageDelegate = self
        
        if indexPath.item == arrayList.count  {
            cell.image = nil
        }else{
            
            cell.image = arrayList[indexPath.item]
        }
       
        return cell
    }

}

//MARK: -实现代理方法
extension appendPhotosCollectionView:appendPhotosCollectionViewCellDelegate{
    
    /// 实现添加图片的代理方法
    @objc private func appendPhotosCollectionViewCellfunc(){
        
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            print("无法访问图库")
            return
        }
        
        //显示图片显示器
        let picker = UIImagePickerController()
        
        //设置图片选择器的代理
        picker.delegate = self
        //将图库model出来
        
        
       // print("调用代理方法了")
        var tempArray = [UIImage]()
        tempArray.append(UIImage(named: "new_feature_\(random() % 3 + 1)")!)
        arrayList = tempArray + arrayList
        reloadData()
        
    }
    /// 实现更换图片
    @objc private func imgeviewReoptionImage() {
       // print("更换图片")
    }
    /// 实现删除图片
    @objc private func removeButImage(){
        
    }
}

// MARK: - 实现获取相册中的图片的方法
extension appendPhotosCollectionView: UIImagePickerControllerDelegate , UINavigationControllerDelegate{
    
    /// 照片选择完成会调用这个方法
    ///
    /// - parameter picker:      picker
    /// - parameter image:       图片
    /// - parameter editingInfo: 返回数据的详细信息
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
    }
}


//MARK: -appendPhotosCollectionViewCellDelegate声明代理方法
@objc
private protocol appendPhotosCollectionViewCellDelegate: NSObjectProtocol {
    //添加图片
  optional func appendPhotosCollectionViewCellfunc()
    //更换图片
  optional func imgeviewReoptionImage()
    //声明删除图片方法
    optional func removeButImage()
}

// MARK: -collviewcell的自定义
private class appendPhotosCollectionViewCell: UICollectionViewCell, UIImagePickerControllerDelegate , UINavigationControllerDelegate{
    
    //申明代理对象代理
    weak var appimageDelegate : appendPhotosCollectionViewCellDelegate?
    
    override init(frame:CGRect){
        super.init(frame: frame)
       setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 设置cell在面控件的ui
    func setupUI(){
        
        //添加控件
        contentView.addSubview(imageviewBut)
        contentView.addSubview(removeBut)
        
        //自动布局
        imageviewBut.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(contentView.snp_center)
            make.width.equalTo(contentView.snp_width)
            make.height.equalTo(contentView.snp_height)
        }
        
        removeBut.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        
    }
    /// 按钮监听的方法
  @objc private func removeButClick(){
    
        appimageDelegate!.removeButImage!()
    
    }
    //添加图片的按钮
   @objc private func addImage(){
    
//    if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
//        print("无法访问图库")
//        return
//    }
//    
//    //显示图片显示器
//    let picker = UIImagePickerController()
//    
//    //设置图片选择器的代理
//    picker.delegate = self
    
    
    
    
    
    appimageDelegate!.appendPhotosCollectionViewCellfunc!()
        
    }
    //点击含有图片的按钮的、进行更换图片
    @objc private func reoptionImage(){
       
       appimageDelegate!.imgeviewReoptionImage!()
    }
    

    var image: UIImage? {
    //设置按钮的图片
        didSet{
            if image == nil {
               imageviewBut.setImage(UIImage(named: "compose_pic_add")!, forState: .Normal)
                imageviewBut.addTarget(self, action: "addImage", forControlEvents: UIControlEvents.TouchUpInside)
            }else{
                imageviewBut.removeTarget(self, action: "addImage", forControlEvents: UIControlEvents.TouchUpInside)
                imageviewBut.setImage(image, forState: .Normal)
                imageviewBut.addTarget(self, action: "reoptionImage", forControlEvents: UIControlEvents.TouchUpInside)
            }
            imageviewBut.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
            imageviewBut.imageView?.clipsToBounds = true
        }
    }
    
    /// 懒加载cell上面的控件
    private lazy var imageviewBut:UIButton = UIButton()
    
    private lazy var removeBut:UIButton = {
        
      let but = UIButton(imageName: "compose_photo_close")
        
        but.sizeToFit()
        
        but.addTarget(self, action: "removeButClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return but
    }()
}
